<?php
namespace Sfsn\Lib;

class WxChat
{

    /**
     * 发送方帐号（一个OpenID）
     *
     * @var unknown
     */
    private $fromUsername;

    /**
     * 开发者微信号
     *
     * @var unknown
     */
    private $toUsername;

    /**
     * 消息创建时间 （整型）
     *
     * @var unknown
     */
    private $times;

    /**
     * 请求的信息类型 text,image,location...
     *
     * @var unknown
     */
    private $type;

    /**
     * 消息id，64位整型
     *
     * @var unknown
     */
    private $msgid;

    /**
     * 自行修改自己的token
     *
     * @var unknown
     */
    private $token = 'weiXXX';

    /**
     *
     * @var unknown
     */
    private $postStr;

    private $postObj;

    /**
     * 文本消息内容
     *
     * @var unknown
     */
    private $keyword;

    /**
     * 地理位置纬度
     *
     * @var unknown
     */
    private $location_x;

    /**
     * 地理位置经度
     *
     * @var unknown
     */
    private $location_y;

    /**
     * 地图缩放大小
     *
     * @var unknown
     */
    private $scale;

    /**
     * 地理位置信息
     *
     * @var unknown
     */
    private $label;

    /**
     * 消息标题
     *
     * @var unknown
     */
    private $title;

    /**
     * 消息描述
     *
     * @var unknown
     */
    private $description;

    /**
     * 消息链接
     *
     * @var unknown
     */
    private $url;

    /**
     * 事件类型，subscribe(订阅)、unsubscribe(取消订阅)、CLICK(自定义菜单点击事件)
     *
     * @var unknown
     */
    private $event;

    /**
     * 事件KEY值，与自定义菜单接口中KEY值对应
     *
     * @var unknown
     */
    private $eventkey;
    
    // 构造函数
    function __construct()
    {
        $this->postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
        $this->responseMsg(); // 初始化数据
    }
    
    // 拦截器(__get)
    private function __get($_key)
    {
        return $this->$_key;
    }
    
    // 微信封装类
    // type: text 文本类型, news 图文类型
    // text,array(内容),array(ID)
    // news,array(array(标题,介绍,图片,超链接),...小于10条),array(条数,ID)
    // location,array(),array(ID)
    public function fun_xml($type, $value_arr, $o_arr = array(0))
    {
        // =================xml header============
        $con = "
        {$this->fromUsername}
        {$this->toUsername}
        {$this->times}";
        if ($type == 'text_link') {
            $con .= "text";
        } else {
            $con .= "{$type}";
        }
        
        // =================type content============
        switch ($type) {
            case "text": // 1.回复文本消息
                $con .= "{$value_arr[0]}";
                break;
            case "text_link": // 1.回复文本消息带超链接
                $con .= "{$value_arr[0]}";
                break;
            
            case "news": // 2.回复图文消息
                $con .= "{$o_arr[0]}
                ";
                foreach ($value_arr as $id => $v) {
                    if ($id >= $o_arr[0])
                        break;
                    else
                        null; // 判断数组数不超过设置数
                    $con .= "
    
                    {$v[1]}
                    {$v[2]}
                    {$v[3]}
                    ";
                }
                $con .= "";
                break;
            case "music": // 3.回复音乐消息
                $con .= "
                {$value_arr[1]}
                {$value_arr[2]}
                {$value_arr[3]}
                ";
                break;
        } // end switch
          
        // =================end return============
        echo $con . "";
    }
    
    // 初始化基本数据
    private function responseMsg()
    {
        if (! empty($this->postStr)) {
            $this->postObj = simplexml_load_string($this->postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            $this->fromUsername = $this->postObj->FromUserName;
            $this->toUsername = $this->postObj->ToUserName;
            $this->times = time();
            $this->type = $this->postObj->MsgType;
            switch ($this->type) {
                case 'text': // 文本消息
                    $this->responseTest();
                    break;
                case 'image': // 图片消息
                    $this->responseImage();
                    break;
                case 'location': // 地理位置消息
                    $this->responseLocation();
                    break;
                case 'link': // 链接消息
                    $this->responseLink();
                    break;
                case 'event': // 事件推送
                    $this->responseEvent();
                    break;
            }
        } else {
            echo "this a file for weixin API!";
            exit();
        }
    }
    // 文本消息
    private function responseTest()
    {
        $this->keyword = trim($this->postObj->Content);
        $this->msgid = $this->postObj->MsgId;
    }
    // 图片消息
    private function responseImage()
    {
        $this->PicUrl = trim($this->postObj->PicUrl);
        $this->msgid = $this->postObj->MsgId;
    }
    // 地理位置消息
    private function responseLocation()
    {
        $this->location_x = $this->postObj->Location_X;
        $this->location_y = $this->postObj->Location_Y;
        $this->scale = $this->postObj->Scale;
        $this->label = $this->postObj->Label;
        $this->msgid = $this->postObj->MsgId;
    }
    // 链接消息
    private function responseLink()
    {
        $this->title = trim($this->postObj->Title);
        $this->description = trim($this->postObj->Description);
        $this->url = trim($this->postObj->Url);
        $this->msgid = $this->postObj->MsgId;
    }
    // 事件推送
    private function responseEvent()
    {
        $this->event = trim($this->postObj->Event);
        $this->eventkey = trim($this->postObj->EventKey);
    }

    /**
     * 对请求进行校验，若确认此次GET请求来自微信服务器
     * 
     * @param unknown $echoStr            
     * @param unknown $signature            
     * @param unknown $timestamp            
     * @param unknown $nonce            
     * @return unknown|string
     */
    public function valid($echoStr, $signature, $timestamp, $nonce)
    {
        $tmpArr = array(
            $this->token,
            $timestamp,
            $nonce
        );
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);
        if ($tmpStr == $signature) {
            return $echoStr;
        } else {
            return "request error!! Your request is not from weixin server";
            exit();
        }
    }
}
